<?php

namespace App\Http\Controllers;

use App\Models\MchOrder;
use App\Models\Red;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WxPayController extends Controller
{
    public function sendRed()
    {
        // {
        //"appid":"wx599af948b0eea164",
        //"bank_type":"OTHERS",
        //"cash_fee":"1",
        //"fee_type":"CNY",
        //"is_subscribe":"N",
        //"mch_id":"1484795872",
        //"nonce_str":"619c99e930368",
        //"openid":"o8FPis4rlUgO7Te9wLa13Xx_dSQE",
        //"out_trade_no":"324211637652968",
        //"result_code":"SUCCESS",
        //"return_code":"SUCCESS",
        //"sign":"6C3C9B743863214A52D513AE9BB2C422",
        //"time_end":"20211123153615",
        //"total_fee":"1",
        //"trade_type":"JSAPI",
        //"transaction_id":"4200001181202111233756720243"}
        $WechatPay = $this->wechatPay();
        $response = $WechatPay->handlePaidNotify(function($message, $fail) {
            if($message["return_code"] == "SUCCESS") {
                DB::beginTransaction();
                try {
                    $MchOrder = MchOrder::where("order_id",$message["out_trade_no"])->first();
                    if($message["result_code"] == "SUCCESS") {
                        // 支付成功
                        $MchOrder->status = 2;
                        $MchOrder->save();
                        // 修改红包状态
                        Red::where("id",$MchOrder->source_id)->update(["status"=>2,'pay_type'=>2]);
                    } else {
                        // 支付失败
                        $MchOrder->status = 6;
                        $MchOrder->save();
                        Red::where("id",$MchOrder->source_id)->update(["status"=>6]);
                    }
                    DB::commit();
                }catch (\PDOException $e) {
                    DB::rollBack();
                    return $fail('处理订单状态失败');
                }
                return true;

            } else {
                return $fail('通信失败');
            }
        });
        return $response;
    }
}
